//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    refuseTime: 0,
    userInfo: {},
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  //事件处理函数
  bindViewTap: function () {
    let memberStatus = app.globalData.userInfo.memberStatus
      if (memberStatus == 0) {
        wx.getSetting({
          success: res => {
            if (res.authSetting['scope.userInfo']) {
              wx.getUserInfo({
                success: res => {
                  this.decryptUserInfo(res)
                }
              })
            }
          }
        })
      } else if (memberStatus == 1) {
        wx.redirectTo({
          url: '../completeInfo/completeInfo'
        })
      } else if (memberStatus == 2) {
        wx.switchTab({
          url: '../index/index'
        })
      }
  },
  onLoad: function () {
    if (app.globalData.userInfo) {
      this.bindViewTap()
    } else {
      app.wxloginCallback = res => {
        app.globalData.userInfo = res.data.result
        this.bindViewTap()
      }
    }
  },
  getUserInfo: function (e) {
    if (e.detail.errMsg === 'getUserInfo:ok') {
      this.decryptUserInfo(e.detail)
    } else {
      this.data.refuseTime++
      this.setData({
        refuseTime: this.data.refuseTime++
      })
    }
  },
  decryptUserInfo: function (e) {
    if (app.globalData.userInfo.sessionKey) {
      wx.request({
        url: app.globalData.prefix + "/wxAction/userInfo.do",
        data: {
          sessionKey: app.globalData.userInfo.sessionKey,
          encryptedData: e.encryptedData,
          rawData: e.rawData,
          signature: e.signature,
          iv: e.iv
        },
        success: (res) => {
          let status = res.data.status
          if (status == "00") {
            let data = res.data.result
            app.globalData.userInfo = data
            let memberStatus = data.memberStatus
            if (memberStatus == 1) {
              wx.redirectTo({
                url: '../completeInfo/completeInfo'
              })
            } else if (memberStatus == 2) {
              wx.switchTab({
                url: '../index/index'
              })
            }
          } else {
            wx.$showToast(res.data.errorMsg)
          }
        }
      })
    }
  }
})